/**
 * 对页面上输入的密码进行加密传输给后台进行验证，对返回的数据进行解密，在页面展示
 */
let CryptoJS = require('crypto-js') // 引入AES源码js
const AesKey = 'COE_MTR_20240301'

export default {
  encode (str) {
    // 对字符串进行编码
    var encode = encodeURI(str);
    // 对编码的字符串转化base64
    var base64 = btoa(encode);
    return base64;
  },
  decode (base64) {
    // 对base64转编码
    var decode = atob(base64);
    // 编码转字符串
    var str = decodeURI(decode);
    return str;
  },
  encrypt (word, keyStr, ivStr) {
    keyStr = keyStr ? keyStr : AesKey
    ivStr = ivStr ? ivStr : AesKey
    let key = CryptoJS.enc.Utf8.parse(keyStr)
    let iv = CryptoJS.enc.Utf8.parse(ivStr)
    let srcs = CryptoJS.enc.Utf8.parse(word)

    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      // padding: CryptoJS.pad.ZeroPadding,
      padding: CryptoJS.pad.Pkcs7,
    })
    return encrypted.toString()
  },
  // 解密
  decrypt (word, keyStr, ivStr) {
    keyStr = keyStr ? keyStr : AesKey
    ivStr = ivStr ? ivStr : AesKey
    var key = CryptoJS.enc.Utf8.parse(keyStr)
    let iv = CryptoJS.enc.Utf8.parse(ivStr)

    var decrypt = CryptoJS.AES.decrypt(word, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    })
    return decrypt.toString(CryptoJS.enc.Utf8)
  },
}
